<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      title="添加关联"
      @ok="handleSubmit"
      :closeFunc="handleClose"
    >
      <BasicForm @register="registerForm">
        <template #jsonSlot="{ model, field }">
          <CodeEditor v-model:value="model[field]" :mode="modeValue" />
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { defineEmits, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { addAssociationSchemas } from './addModal.data';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const emit = defineEmits(['success', 'register']);
  let optionValue = ref('');
  let key = ref('');
  const modeValue = ref<MODE>(MODE.JSON);
  const [registerForm, { validate, resetSchema, updateSchema, resetFields }] = useForm({
    layout: 'vertical',
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async ({ optionsValue, keyName }) => {
      setModalProps({ loading: true, confirmLoading: true, ...modalStyleSetting });
      optionValue.value = optionsValue;
      key.value = keyName;
      resetSchema(addAssociationSchemas);
      if (optionsValue.value == 'to') {
        updateSchema({ field: 'toEntity', label: '从实体' });
      }

      setModalProps({ loading: false, confirmLoading: false });
    },
  );

  const handleClose = async () => {
    resetFields();
    return true;
  };

  const handleSubmit = async () => {
    setModalProps({ confirmLoading: true });
    try {
      const values = await validate();
      closeModal();
      emit('success', {
        key: 'add',
        values: { ...values, optionsValue: optionValue.value },
      });
      resetFields();
    } catch (e) {}
    setModalProps({ confirmLoading: false });
  };
</script>
